import { request } from '@/utils/request'
import type { ApiResponse } from '@/types/api'

export interface Source {
  _id?: string
  id?: string
  name: string
  code: string
  module_type: string
  description?: string
  color?: string
  sort_order?: number
  is_enabled?: boolean
  created_at?: string
  updated_at?: string
}

export interface SourceCreate {
  name: string
  code: string
  module_type: string
  description?: string
  color?: string
  sort_order?: number
  is_enabled?: boolean
}

export interface SourceUpdate {
  name?: string
  code?: string
  description?: string
  color?: string
  sort_order?: number
  is_enabled?: boolean
}

export const sourceApi = {
  // 获取来源列表
  getAll: (moduleType?: string, includeDisabled = false) => {
    const params: any = {}
    if (moduleType) {
      params.module_type = moduleType
    }
    if (includeDisabled) {
      params.include_disabled = true
    }
    return request.get<ApiResponse<Source[]>>('/sources/', { params }).then(res => res.data)
  },

  // 获取所有模块的来源选项
  getAllOptions: (forceRefresh = false) => {
    return request.get<ApiResponse<Record<string, any[]>>>('/sources/all/options', {
      params: { force_refresh: forceRefresh }
    }).then(res => res.data)
  },

  // 获取来源详情
  getById: (id: string) => {
    return request.get<ApiResponse<Source>>(`/sources/${id}`).then(res => res.data)
  },

  // 创建来源
  create: (data: SourceCreate) => {
    return request.post<ApiResponse<Source>>('/sources/', data).then(res => res.data)
  },

  // 更新来源
  update: (id: string, data: SourceUpdate) => {
    return request.put<ApiResponse<Source>>(`/sources/${id}`, data).then(res => res.data)
  },

  // 删除来源
  delete: (id: string) => {
    return request.delete<ApiResponse<{ id: string }>>(`/sources/${id}`).then(res => res.data)
  },

  // 刷新缓存
  refreshCache: (moduleType?: string) => {
    const params: any = {}
    if (moduleType) {
      params.module_type = moduleType
    }
    return request.post<ApiResponse<any>>('/sources/cache/refresh', null, { params }).then(res => res.data)
  },

  // 初始化默认来源
  initialize: (moduleType: string) => {
    return request.post<ApiResponse<{ created_count: number }>>('/sources/initialize', null, {
      params: { module_type: moduleType }
    }).then(res => res.data)
  }
}


